package coroutines.coroutinebuilder

import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.Exception
import java.util.concurrent.CancellationException

class JobTest {
}

fun main() {
    val job = GlobalScope.launch(start = CoroutineStart.LAZY) {
        // 每循环一次均延迟100毫秒
        for (i in 0..100) {
            delay(100)
        }
    }

    job.invokeOnCompletion {
        println()
        println("invokeOnCompletion: $it")
    }

    println()
    println("1. launch(start = CoroutineStart.LAZY)")
    println("1. job.isActive: ${job.isActive}")
    println("1. job.isCancelled: ${job.isCancelled}")
    println("1. job.isCompleted: ${job.isCompleted}")

    job.start()

    println()
    println("1. start()")
    println("2. job.isActive: ${job.isActive}")
    println("2. job.isCancelled: ${job.isCancelled}")
    println("2. job.isCompleted: ${job.isCompleted}")

    try {
        Thread.sleep(400)
        job.cancel(CancellationException("test"))
    } catch (e: Exception) {
        e.printStackTrace()
    }

    try {
        Thread.sleep(400)
    } catch (e: Exception) {
        e.printStackTrace()
    }

    println()
    println("1. cancel()")
    println("2. job.isActive: ${job.isActive}")
    println("2. job.isCancelled: ${job.isCancelled}")
    println("2. job.isCompleted: ${job.isCompleted}")
}